package com.aipartner.controller;

import com.aipartner.common.PageResult;
import com.aipartner.common.Result;
import com.aipartner.dto.ChatRequest;
import com.aipartner.dto.ChatResponse;
import com.aipartner.entity.ChatHistory;
import com.aipartner.service.AiService;
import com.aipartner.service.ChatHistoryService;
import com.aipartner.util.UserContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

/**
 * Chat Controller
 * 
 * @author AI Partner Team
 * @since 2024-01-20
 */
@Api(tags = "Chat Management")
@RestController
@RequestMapping("/api/chat")
@RequiredArgsConstructor
@Slf4j
@Validated
public class ChatController {
    
    private final AiService aiService;
    private final ChatHistoryService chatHistoryService;
    
    @ApiOperation("Send Chat Message")
    @PostMapping("/send")
    public Result<ChatResponse> sendMessage(@Valid @RequestBody ChatRequest request) {
        try {
            // 从上下文获取用户ID，避免前端必须传userId
            Long currentUserId = UserContext.getCurrentUserId();
            if (currentUserId == null && request.getUserId() == null) {
                return Result.fail("User not logged in");
            }
            if (request.getUserId() == null) {
                request.setUserId(currentUserId);
            }
            ChatResponse response = aiService.chat(request);
            return Result.success(response, "Chat completed successfully");
        } catch (Exception e) {
            log.error("Chat error: {}", e.getMessage(), e);
            return Result.fail("Chat failed: " + e.getMessage());
        }
    }
    
    @ApiOperation("Get Chat History by User")
    @GetMapping("/history")
    public PageResult<ChatHistory> getChatHistory(
            @ApiParam("Page number") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("Page size") @RequestParam(defaultValue = "20") Integer size,
            @ApiParam("Session ID") @RequestParam(required = false) String sessionId,
            @ApiParam("Model name") @RequestParam(required = false) String modelName) {
        
        Long userId = UserContext.getCurrentUserId();
        return chatHistoryService.getUserChatHistory(userId, page, size, sessionId, modelName);
    }
    
    @ApiOperation("Get Chat History by Session")
    @GetMapping("/history/session/{sessionId}")
    public PageResult<ChatHistory> getSessionHistory(
            @ApiParam("Session ID") @PathVariable String sessionId,
            @ApiParam("Page number") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("Page size") @RequestParam(defaultValue = "50") Integer size) {
        
        Long userId = UserContext.getCurrentUserId();
        return chatHistoryService.getSessionHistory(sessionId, userId, page, size);
    }
    
    @ApiOperation("Delete Chat History")
    @DeleteMapping("/history/{id}")
    public Result<Void> deleteChatHistory(@ApiParam("History ID") @PathVariable @NotNull Long id) {
        Long userId = UserContext.getCurrentUserId();
        boolean deleted = chatHistoryService.deleteChatHistory(id, userId);
        return deleted ? Result.success(null, "Chat history deleted successfully") 
                      : Result.fail("Failed to delete chat history");
    }
    
    @ApiOperation("Clear All Chat History")
    @DeleteMapping("/history/clear")
    public Result<Void> clearChatHistory() {
        Long userId = UserContext.getCurrentUserId();
        boolean cleared = chatHistoryService.clearUserChatHistory(userId);
        return cleared ? Result.success(null, "All chat history cleared successfully")
                      : Result.fail("Failed to clear chat history");
    }
}